import 'dart:async';

import '../../domain/repositories/project_repository.dart';
import '../datasources/remote/project_api_service.dart';
import '../datasources/local/local_data_source.dart';
import '../models/project_model.dart';
import '../models/api_response.dart';
import '../../core/offline/offline_mode_manager.dart';

/// 项目仓储实现类
class ProjectRepositoryImpl implements ProjectRepository {
  final ProjectApiService _apiService;
  final LocalDataSource _localDataSource;
  final OfflineModeManager _offlineModeManager;

  ProjectRepositoryImpl(
    this._apiService,
    this._localDataSource,
    this._offlineModeManager,
  );

  @override
  Future<ProjectModel> createProject(ProjectCreateRequest request) async {
    try {
      // 检查当前是否为离线模式
      if (_offlineModeManager.currentStatus == OfflineModeStatus.offline) {
        // 离线模式下无法创建项目
        throw Exception('离线模式下无法创建项目');
      }

      // 在线模式下创建项目
      final response = await _apiService.createProject(request);

      if (response.success && response.data != null) {
        final project = response.data!;

        // 同步到本地数据源
        await _localDataSource.saveProject(project);

        return project;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('创建项目失败: ${e.toString()}');
    }
  }

  @override
  Future<ProjectModel> updateProject(
      int projectId, ProjectUpdateRequest request) async {
    try {
      // 检查当前是否为离线模式
      if (_offlineModeManager.currentStatus == OfflineModeStatus.offline) {
        // 离线模式下无法更新项目
        throw Exception('离线模式下无法更新项目');
      }

      // 在线模式下更新项目
      final response = await _apiService.updateProject(projectId, request);

      if (response.success && response.data != null) {
        final project = response.data!;

        // 同步到本地数据源
        await _localDataSource.saveProject(project);

        return project;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('更新项目失败: ${e.toString()}');
    }
  }

  @override
  Future<void> deleteProject(int projectId) async {
    try {
      // 检查当前是否为离线模式
      if (_offlineModeManager.currentStatus == OfflineModeStatus.offline) {
        // 离线模式下无法删除项目
        throw Exception('离线模式下无法删除项目');
      }

      // 在线模式下删除项目
      final response = await _apiService.deleteProject(projectId);

      if (response.success) {
        // 同步删除本地数据
        await _localDataSource.deleteProject(projectId);
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('删除项目失败: ${e.toString()}');
    }
  }

  @override
  Future<ProjectModel> getProject(int projectId) async {
    try {
      // 检查当前是否为离线模式
      if (_offlineModeManager.currentStatus == OfflineModeStatus.offline) {
        // 离线模式下从本地数据源获取项目
        final localProject = await _localDataSource.findProjectById(projectId);
        if (localProject != null) {
          return localProject;
        } else {
          throw Exception('项目不存在');
        }
      }

      // 在线模式下从远程API获取项目
      final response = await _apiService.getProject(projectId);

      if (response.success && response.data != null) {
        final project = response.data!;

        // 同步到本地数据源
        await _localDataSource.saveProject(project);

        return project;
      } else {
        // 如果远程获取失败，尝试从本地数据源获取
        final localProject = await _localDataSource.findProjectById(projectId);
        if (localProject != null) {
          return localProject;
        } else {
          throw Exception(response.message);
        }
      }
    } catch (e) {
      // 出现异常时，尝试从本地数据源获取
      try {
        final localProject = await _localDataSource.findProjectById(projectId);
        if (localProject != null) {
          return localProject;
        } else {
          throw Exception('获取项目详情失败: ${e.toString()}');
        }
      } catch (localError) {
        throw Exception('获取项目详情失败: ${e.toString()}');
      }
    }
  }

  @override
  Future<PageResponse<ProjectModel>> getProjects({
    ProjectStatus? status,
    int? creatorId,
    String? keyword,
    int page = 0,
    int size = 10,
  }) async {
    try {
      // 检查当前是否为离线模式
      if (_offlineModeManager.currentStatus == OfflineModeStatus.offline) {
        // 离线模式下从本地数据源获取数据
        final localProjects = await _localDataSource.getAllProjects();
        // 创建一个模拟的分页响应
        final pageResponse = PageResponse<ProjectModel>(
          content: localProjects,
          totalElements: localProjects.length,
          totalPages: 1,
          currentPage: 0,
          size: localProjects.length,
          first: true,
          last: true,
          hasNext: false,
          hasPrevious: false,
        );
        return pageResponse;
      }

      // 在线模式下从远程API获取数据
      final response = await _apiService.getProjects(
        status: status,
        creatorId: creatorId,
        keyword: keyword,
        page: page,
        size: size,
      );

      if (response.success && response.data != null) {
        final pageResponse = response.data!;
        final projects = pageResponse.content;

        // 同步到本地数据源
        for (final project in projects) {
          await _localDataSource.saveProject(project);
        }

        return pageResponse;
      } else {
        // 如果远程获取失败，尝试从本地数据源获取
        final localProjects = await _localDataSource.getAllProjects();
        // 创建一个模拟的分页响应
        final pageResponse = PageResponse<ProjectModel>(
          content: localProjects,
          totalElements: localProjects.length,
          totalPages: 1,
          currentPage: 0,
          size: localProjects.length,
          first: true,
          last: true,
          hasNext: false,
          hasPrevious: false,
        );
        return pageResponse;
      }
    } catch (e) {
      // 出现异常时，尝试从本地数据源获取
      try {
        final localProjects = await _localDataSource.getAllProjects();
        // 创建一个模拟的分页响应
        final pageResponse = PageResponse<ProjectModel>(
          content: localProjects,
          totalElements: localProjects.length,
          totalPages: 1,
          currentPage: 0,
          size: localProjects.length,
          first: true,
          last: true,
          hasNext: false,
          hasPrevious: false,
        );
        return pageResponse;
      } catch (localError) {
        throw Exception('获取项目列表失败: ${e.toString()}');
      }
    }
  }

  @override
  Future<List<ProjectModel>> getMyProjects() async {
    try {
      // 检查当前是否为离线模式
      if (_offlineModeManager.currentStatus == OfflineModeStatus.offline) {
        // 离线模式下从本地数据源获取我的项目
        final localProjects = await _localDataSource.getAllProjects();
        return localProjects;
      }

      // 在线模式下从远程API获取我的项目
      final response = await _apiService.getMyProjects();

      if (response.success && response.data != null) {
        final projects = response.data!;

        // 同步到本地数据源
        for (final project in projects) {
          await _localDataSource.saveProject(project);
        }

        return projects;
      } else {
        // 如果远程获取失败，尝试从本地数据源获取
        final localProjects = await _localDataSource.getAllProjects();
        return localProjects;
      }
    } catch (e) {
      // 出现异常时，尝试从本地数据源获取
      try {
        final localProjects = await _localDataSource.getAllProjects();
        return localProjects;
      } catch (localError) {
        throw Exception('获取我的项目失败: ${e.toString()}');
      }
    }
  }

  @override
  Future<List<ProjectModel>> getProjectsNearDeadline() async {
    // 这个方法在离线模式下可能需要特殊处理
    // 暂时直接调用API服务
    final response = await _apiService.getProjectsNearDeadline();
    if (response.success && response.data != null) {
      return response.data!;
    } else {
      throw Exception(response.message);
    }
  }

  @override
  Future<List<ProjectModel>> getOverdueProjects() async {
    // 这个方法在离线模式下可能需要特殊处理
    // 暂时直接调用API服务
    final response = await _apiService.getOverdueProjects();
    if (response.success && response.data != null) {
      return response.data!;
    } else {
      throw Exception(response.message);
    }
  }

  @override
  Future<void> cacheProjects(List<ProjectModel> projects) async {
    // 缓存项目到本地数据源
    for (final project in projects) {
      await _localDataSource.saveProject(project);
    }
  }

  @override
  Future<List<ProjectModel>?> getCachedProjects() async {
    // 从本地数据源获取缓存的项目
    return await _localDataSource.getAllProjects();
  }

  @override
  Future<void> clearProjectCache() async {
    // 清除本地项目缓存的逻辑
    // 这里可以根据实际需求实现，比如清除所有项目数据
    // 暂时留空
  }
}
